// 问题
const Question = require('../models/question')
class QuestionController {
    // ===================问题搜索==================
    async getQuestionlist(ctx) {
      // 分页逻辑
      let { perPage = 10, page = 1}  = ctx.query // 默认每页十条数据，从第一页起步
      // 防止输入负数
      perPage = Math.max(perPage * 1, 1) 
      page = Math.max(page * 1,1) 
      
      // 关键词，描述或者题目名
      const q = new RegExp(ctx.query.q)

      const questionList = await Question.find( {$or: [{title: q}, {description: q}]}).limit(perPage).skip((page-1) * perPage)  // limit限制查询数量、skip跳过多少条记录
      ctx.body = questionList
    }

    // =======================检查问题是否存在======================
    async checkQuestionExist(ctx, next) {
      const question  = await Question.findById(ctx.params.id).select('+questioner');
      if (!question) {
        ctx.throw(404, '问题不存在！')
      }
      ctx.state.question = question // 问题存在，保存到state中
      await next()
    }

    // ========================查找特定的问题====================
    async findQuestionById(ctx) {
    const fields = ctx.query.fields || ''
    const selectFields = fields.split(';').filter(item=>item).map(item=> ' +'+item).join('')
    // 问题创建者填充user、话题topic的信息
    const question = await Question.findById(ctx.params.id).select(selectFields).populate('questioner topics')
    ctx.body = question
    }

    // =======================创建问题==========================
    async createQuestion(ctx) {
      ctx.verifyParams({
        title: {type: 'string', required: true},
        description: {type: 'string', required: false},
        questioner: {type: 'string', required: false}
      })
      // 不允许重复创建相同的问题
      const isExist = await Question.findOne({title: ctx.request.body.title})
      if(!isExist) {
        const question  = await Question({...ctx.request.body,questioner: ctx.state.user.userId}).save()
        ctx.body = question
        ctx.status = 204
      } else {
        ctx.throw(409, '问题已存在')
      }
    }

    // ===========================更新问题=========================
    async updatedQuestion(ctx) {
      ctx.verifyParams({
        title: {type: 'string', required: true},
        description: {type: 'string', required: false}
      })
      // 请求更新前会检查问题是否存在，直接从state中读取question
     const question = await Question.findByIdAndUpdate(ctx.params.id, ctx.request.body, {new: true})
      ctx.body = question
    }

    // ==========================删除问题========================
    async deleteQuestion(ctx) {
      // 问题的拥有者才能删除问题
      const { question } = ctx.state
      if (question.questioner.toString() === ctx.state.user.userId) {
        await Question.findByIdAndRemove(ctx.params.id)
        ctx.status = 204
      } else {
        ctx.throw(403, '没有权限')
      }
    }
}

module.exports = new QuestionController()